/**
 * https://leetcode.cn/problems/find-k-closest-elements/submissions/559945201/
 * 658. 找到 K 个最接近的元素
 * medium, 陈贝纯 2024/08/30
 * 滑动窗口
 */

class Solution {
public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        int i=0;
        int leng=arr.size()-1;
        while(i<arr.size()&&arr[i]<x)
        i++;
        int l=max(0,i-k);
        int r=min(leng,i+k);
        if(i<arr.size()&&arr[i]>x){
            r=min(leng,i+k-1);
        }
        while(r-l>=k){
                if(x-arr[l]>arr[r]-x)
                l++;
                else
                r--;
            }
        vector<int> v;
        for(int i=l;i<=r;i++)
        v.push_back(arr[i]);
        return v;
    }
};

